package com.frank.chapter412.codegen;

import com.frank.chapter412.utils.CamelUnderlineTransformUtils;
import lombok.extern.slf4j.Slf4j;
import org.jooq.util.JavaWriter;

import java.io.File;

/**
 * Created by HYL on 2016/11/11.
 */
@Slf4j
public class GenerationService {

    private static String serviceBasePackage = "com.frank.chapter412.service.";
    private static String serviceDir = "src/main/java/";

    public static void deleteService(String dbName, String className) {
        File file = new File((serviceDir + serviceBasePackage + dbName + "." + className + "Service").replaceAll("\\.", "/") + ".java");
        log.info("delete service => " + file.getAbsolutePath());
        file.delete();
    }

    public static void generator(String db, String tableName) {

        String dir = serviceDir;

        String packageName = serviceBasePackage + db.replaceAll("_", "");
        tableName = CamelUnderlineTransformUtils.underlineToCamel(tableName);
        String className = tableName + "Service";
        className = className.replaceFirst(className.substring(0, 1), className.substring(0, 1).toUpperCase());

        try {
            Class.forName(packageName + "." + className);
            log.info("service " + className + " already exist. pass");
        } catch (ClassNotFoundException e) {
            log.info("generator service => " + className);

            dir += packageName.replaceAll("\\.", "/") + "/";

            File file = new File(dir + className + ".java");
            JavaWriter out = new JavaWriter(file, "");

            out.println("/**");
            out.println(" * This class is generated by GenerationCodeUtil.");
            out.println("*/");

            out.println();
            out.println("package %s;", packageName);
            out.println("import org.springframework.stereotype.Service;\n");

            out.println();
            out.println("@Service");
            out.println("public class %s {", className);
            out.println();
            out.println("}");
            out.close();
        }


    }

    public static void main(String[] args) {
        generator("dada", "area_in");
    }
}
